<template>
  <div class="container">
    <div class="box">
      <div class="box_avatar">
        <img src="../../assets/realize.jpg" alt="">
      </div>
      <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="100px" class="box_form">
        <el-form-item
          label="账户名称"
          prop="username"
          :rules="[
            { required: true, message: '请输入账户名称', trigger: ['blur', 'change'] },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ]"
        >
          <el-input v-model="ruleForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input v-model="ruleForm.checkPassword" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="email"
          label="邮箱"
          :rules="[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ]"
        >
          <el-input v-model="ruleForm.email" />
        </el-form-item>
        <el-form-item id="Code" label="验证码" prop="code">
          <el-input v-model="ruleForm.code" autocomplete="off" />
          <el-button :disabled="btnDisabled" type="warning" @click="getCode('ruleForm',ruleForm.email)">{{ codeBtn }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm'),clickHandler($event)">确认注册</el-button>
          <el-button @click="resetForm('ruleForm'),clickHandler($event)">重置</el-button>
          <el-button style="float: right;" @click="back(),clickHandler($event)">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>

</template>

<script>
import userApi from '@/api/user'

export default {
  beforeRouteLeave(to, from, next) {
    if (this.canvasFlag) {
      this.deleteCanvas()
    }
    next()
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPassword !== '') {
          this.$refs.ruleForm.validateField('checkPassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      // 发送验证码按钮信息
      btnDisabled: false,
      codeBtn: '发送验证码',
      // 这是登录表单的数据绑定对象
      ruleForm: {
        username: '',
        email: '',
        password: '',
        checkPassword: '',
        code: ''
      },
      code: '',
      // 表单验证对象
      rules: {
        username: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      },
      canvasFlag: false
    }
  },
  created() {
    this.$moment.init()
    this.$moment.animate()
    this.canvasFlag = true
  },
  methods: {
    // 表单实例对象，重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 预验证
    getCode(formName, email) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.btnDisabled = true
          let timeLeave = 60
          const count = setInterval(() => {
            timeLeave--
            this.codeBtn = timeLeave + 's后可再次发送'
            if (timeLeave === 0) {
              this.codeBtn = '发送验证码'
              this.btnDisabled = false
              clearInterval(count)
            }
          }, 1000)
          userApi.getEmailCode(email).then(resp => {
            if (resp.data.code === 200) {
              this.$message({
                showClose: true,
                message: '验证码已发送,一分钟内有效',
                type: 'success'
              })
            }
          }, err => {
            console.log(err)
          })
        } else {
          this.$message.error('请准确完成各项输入！')
          return false
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.ruleForm.code) {
          const { code, email, password, username } = this.ruleForm
          if (this.$store.getters.roles.includes('admin')) {
            userApi.adminRegister({ code, email, password, username }).then(resp => {
              if (resp.data.code === 200) {
                this.$message.success('注册成功！')
              } else {
                this.$message.error('请输入正确的验证码！')
              }
            }, err => {
              console.log(err)
            })
          } else {
            userApi.register({ code, email, password, username }).then(resp => {
              if (resp.data.code === 200) {
                this.$message.success('注册成功！')
              } else {
                this.$message.error('请输入正确的验证码！')
              }
            }, err => {
              console.log(err)
            })
          }
        } else {
          this.$message.error('请准确完成各项输入！')
          return false
        }
      })
    },
    deleteCanvas() {
      document.getElementById('wall-bg').remove()
      this.canvasFlag = false
    },
    back() {
      this.$store.getters.roles.includes('user') ? this.$router.push({ path: '/panelChild' }) : this.$router.push({ path: '/userLogin' })
    }
  }
}
</script>

<style scoped>

.container {
    height: 100%;
    margin-top: -730px;
}

.box {
    width: 600px;
    height: 500px;
    background-color: #fff;
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    box-shadow: 0 0 10px 0 rgb(0 33 79 / 11%);
    transform: translate(-50%,-50%);
}

.box .box_avatar {
    height: 130px;
    width: 130px;
    border:1px solid #eee;
    border-radius:50%;
    padding:10px;
    box-shadow:0 0 10px  #ddd;
    position: absolute;
    left: 50%;
    transform: translate(-50%,-50%);
    background-color: #eee;
}

.box .box_avatar img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background-color: #eee;
}

.box_form {
    position: absolute;
    bottom: 40px;
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
}

.box_form >>> .el-form-item {
    width: 80%;
}

#Code >>> .el-form-item__content {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}

#Code >>> .el-input input {
    width: 70%;
    min-width: 165px;
}

</style>
